﻿namespace FluentMvc.MvcIntegration
{
    using System;
    using System.Collections.Generic;
    using System.Web.Mvc;
    using Fasterflect;
    using System.Linq;

    public class FluentValidatorProvider : ModelValidatorProvider
    {
        public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)
        {
            if (metadata.ContainerType == null || !metadata.ContainerType.Constructors().Any(info => info.Parameters().Count == 0))
                return Enumerable.Empty<ModelValidator>();
            if(metadata.ContainerType != null && metadata.ContainerType.IsClass && typeof(IModelInitializer<>).MakeGenericType(metadata.ContainerType).IsAssignableFrom(metadata.ContainerType))
            {
                return new List<ModelValidator>
                           {
                               (ModelValidator) typeof (FluentModelPropertyValidator<>).MakeGenericType(metadata.ContainerType).CreateInstance(metadata, context)
                           };
            }
            return Enumerable.Empty<ModelValidator>();
        }

        public static Action<FluentValidationContext> BeforeValidate;
        public static Action<AfterValidateArgs> AfterValidate; 

        public static void Config()
        {
            DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
            ModelMetadataProviders.Current = new TemplateDataAnnotationsModelMetadataProvider();
            ModelValidatorProviders.Providers.Add(new FluentValidatorProvider());
        }
    }
}